﻿' Copyright (c) Microsoft Corporation.  All rights reserved.
Imports EdmMetadataHelpersVB
Imports System.Data.Metadata.Edm

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Me.IsPostBack Then
            LoadTreeView()
            HideAllDivs()
            ShowNode(SelectedNode)
        End If
    End Sub
    Protected Sub HideAllDivs()
        Me.divEntitySet.Visible = False
    End Sub
    Protected Sub LoadTreeView()
        Dim root As New TreeNode("All Models")
        root.SelectAction = TreeNodeSelectAction.Select
        root.Target = ""
        'Create a node to allow new models to be added
        Dim action As New TreeNode("[Add a model]")
        action.ImageUrl = "assets\newschema.jpg"
        action.SelectAction = TreeNodeSelectAction.Select
        action.Target = "Model"

        root.ChildNodes.Add(action)

        'Make sure we have at least one model to start off with
        If (EdmWrappers.Current.Count = 0) Then
            EdmWrappers.Current.Add(New EdmWrapper("Northwind", _
                                                   "System.Data.SqlClient", _
                                                   "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;User Instance=True", _
                                                   "|DataDirectory|\NorthwindModel.csdl", _
                                                   "|DataDirectory|\NorthwindModel.ssdl", _
                                                   "|DataDirectory|\NorthwindModel.msl"))
        End If
        'Add nodes for each EDM
        For Each edm In EdmWrappers.Current
            root.ChildNodes.Add(edm.GetRootNode())
        Next

        trCSDL.Nodes.Add(root)
    End Sub
    Protected ReadOnly Property SelectedNode() As TreeNode
        Get
            Return trCSDL.SelectedNode
        End Get
    End Property
    Protected Sub ShowModel(ByVal node As TreeNode)
        Response.Redirect(String.Format("EditModel.aspx?Model={0}", node.Value))
    End Sub
    Protected Sub ShowNode(ByVal node As TreeNode)
        If (SelectedNode Is Nothing) Then
            Return
        End If
        Select Case node.Target
            Case "","EntityType", "AssociationType"
                Return
            Case "Model"
                ShowModel(node)
                Return
            Case "EntitySet", "AssociationSet"
                ShowEntitySet(node)
                Return
        End Select

    End Sub
    Protected Sub ShowEntitySet(ByVal node As TreeNode)
        grdResults.Visible = False
        divEntitySet.Visible = True

        Dim edm As EdmWrapper = EdmWrappers.Current.FindByName(node.Parent.Parent.Text)
        Dim entityset As String = node.Value
        Dim container As String = node.Parent.Value
        txtQuery.Text = String.Format("select VALUE E from {0}.{1} as E", container, entityset)

        Dim es As EntitySet = edm.Csdl.EntitySets.Where(Function(eset) eset.Name = node.Text).FirstOrDefault()
        If es Is Nothing Then
            Throw New Exception(String.Format("No EntitySet called '{0}' was found", node.Text))
        End If

        Dim et = es.ElementType
        chkEntitySetColumns.Items.Clear()

        For Each prop In et.Properties
            chkEntitySetColumns.Items.Add(New ListItem(prop.Name, prop.Name))
        Next

    End Sub
    Protected Sub OnNodeSelect(ByVal sender As Object, ByVal e As EventArgs)
        HideAllDivs()
        ShowNode(SelectedNode)
    End Sub
    ''' <summary>
    ''' When a column is selected we rebuild the eSQL for the user.
    ''' </summary>
    Protected Sub chkEntitySetColumns_SelectedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExecuteQuery.Click
        Dim eSQL As String = Nothing

        For Each item In chkEntitySetColumns.Items
            If item.Selected Then
                eSQL = IIf(eSQL Is Nothing, String.Format("E.{0}", item.Value), String.Format("{0}, E.{1} ", eSQL, item.Value))

            End If
        Next
        If eSQL Is Nothing Then
            eSQL = "VALUE E"
        End If

        Dim container = SelectedNode.Parent.Text
        Dim name = SelectedNode.Text

        Dim fullname = container + "." + name

        eSQL = String.Format("SELECT {0} FROM {1} AS E", eSQL, fullname)
        txtQuery.Text = eSQL
    End Sub
    ''' <summary>
    ''' Execute the eSQL against the current Entity Data Model and 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub btnExecuteQuery_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExecuteQuery.Click
        grdResults.Visible = True
        Dim edmName = SelectedNode.Parent.Parent.Value
        Dim eSQL = txtQuery.Text.Trim()
        Dim table = EdmWrappers.Current.FindByName(edmName).GetDataTable(eSQL)
        grdResults.DataSource = table
        grdResults.DataBind()
    End Sub
End Class
